package com.xone.xapp;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

public class GuideActivity extends BasicActivity {

	protected GridView gridView;
	protected Handler advertisement = null;
	protected ViewPager viewPager;
	// 包裹小圆点的LinearLayout
	protected ViewGroup indicator;
	protected ImageView[] imageIndicator;
	protected int columnWidth = 0;
	private Timer timer;
	@Override
	public String getHeaderTitle() {
		return getTitleByLevel("欢迎使用");
	}
	@Override
	public int getContentView() {
		return R.layout.guide;
	} 
	@Override
	public boolean isShowBanner() {
		return false;
	}
	/**
	 * 是否需要检测登录
	 * @return
	 */
	@Override
	public boolean isLoginCheck() {
		return false;
	}
	
	@Override
	public boolean isRefreshButton() {
		return true;
	}
	
	@Override
	public void leftButton(Button leftButton) {
		if (UserInfo.login) {
			leftButton.setText("退出");
			leftButton.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					new AlertDialog.Builder(getContext())
					.setTitle("消息确认")
					.setMessage("确认退出登录吗？")
					.setPositiveButton(android.R.string.ok,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog, int which) {
									showProgress();
									new LogoutDataTask(getContext()) {
										@Override
										public void onFinish(JSONObject resutl) {
											hideProgress();
										}
									}.execute();
								}
							})
					.setNegativeButton(android.R.string.cancel,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog, int which) {
									
								}
							}).create().show();
				}
			});
		} else {
			leftButton.setText("注册");
			leftButton.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					Intent i = new Intent(getContext(), RegisterActivity.class);
					startActivity(i);
				}
			});
		}
	}
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		gridView = (GridView) findViewById(R.id.grid_view);
		//广告部分界面展现的消息
		advertisement = new Handler(new Handler.Callback() {
		    @Override
			public boolean handleMessage(Message msg) {// 定义一个Handler，用于处理下载线程与UI间通讯
				if (Thread.currentThread().isInterrupted()) {
					return false;
				}
				switch (msg.what) {
				case 1://初始化界面上广告处的小点
					Bundle bundle = msg.getData();
					if (null == bundle) {
						break;
					}
					int count = bundle.getInt("count");
					if (count <= 0) {
						break;
					}
					indicator = (ViewGroup)findViewById(R.id.indicator);
					indicator.removeAllViews();
					imageIndicator = new ImageView[count];
					for (int i = 0; i < count; i++) {
						ImageView imageView = new ImageView(GuideActivity.this);
						LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(13, 13);
						layoutParams.setMargins(3, 0, 3, 0);
						imageView.setLayoutParams(layoutParams);
						imageView.setBackgroundColor(Color.TRANSPARENT);
						imageIndicator[i] = imageView;
						if (i == 0) {// 默认选中第一张图片
							imageIndicator[i].setBackgroundResource(R.drawable.page_indicator_focused);
						} else {
							imageIndicator[i].setBackgroundResource(R.drawable.page_indicator);
						}
						indicator.addView(imageIndicator[i]);
					}
					findViewById(R.id.guideadvertise).setVisibility(View.VISIBLE);
					break;
				case 2://切换页面动画
					int viewCount = viewPager.getChildCount();
					if (viewCount > 1) {
						if (null == imageIndicator || imageIndicator.length == 0) {
							break;
						}
						int cItem = viewPager.getCurrentItem();
						cItem ++;
						if (cItem >= viewCount) {
							cItem = 0;
						}
						viewPager.setCurrentItem(cItem, true);
						for (int i = 0; i < imageIndicator.length; i++) {
							if (cItem != i) {
								imageIndicator[i].setBackgroundResource(R.drawable.page_indicator);
							}
						}
						imageIndicator[cItem].setBackgroundResource(R.drawable.page_indicator_focused);
					}
					break;
				}
				return true;
			}
		});
		//下部的图片行为框部分
		Resources r = getResources();
		float padding = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, Constants.GRID_PADDING, r.getDisplayMetrics());
		columnWidth = (int) ((ContextUtils.getScreenWidth(this) - ((Constants.NUM_OF_COLUMNS + 1) * padding)) / Constants.NUM_OF_COLUMNS);
		gridView.setNumColumns(Constants.NUM_OF_COLUMNS);
		gridView.setColumnWidth(columnWidth);
		gridView.setStretchMode(GridView.NO_STRETCH);
		gridView.setPadding((int)padding/2, (int) padding/2, (int)padding/2, (int) padding/2);
		gridView.setHorizontalSpacing((int) padding);
		gridView.setVerticalSpacing((int) padding);
		//广告部分的初始化数据
		viewPager = (ViewPager) findViewById(R.id.guidePages);
		String cache = ShareUtils.getPrefs("links", this);
		if (StringUtils.isNotBlank(cache)) {
			List<JSONObject> result = JSONUtils.getJSONListFromIdentifyString(cache, "links");
			if (null != result && !result.isEmpty()) {
				GuideGridAdapter guideGridAdapter = new GuideGridAdapter(this, result, columnWidth);
				gridView.setAdapter(guideGridAdapter);
			}
		}
	}
	
	protected void onResume() {
		super.onResume();
		showProgress();
		new InitDataTask(this, gridView, columnWidth).execute();//重新取用户设置的数据
		new InitGuideAdvertisementDataTask(this, viewPager).execute();//重新取广告数据
		timer = new Timer();
		timer.schedule(new TimerTask() {
			@Override
			public void run() {
				Message msg = new Message();  
	            msg.what = 2;
	            advertisement.sendMessage(msg);
			}
		}, Constants.ADVERTISEMENT_INTERVAL * 1000, Constants.ADVERTISEMENT_INTERVAL * 1000);
	}
	
	protected void onPause() {
		super.onPause();
		if (null != timer) {
			timer.cancel();
			timer.purge();
		}
		timer = null;
	}
	
	@Override
	public void onBackPressed() {
		super.onBackPressed();
	    this.finish();
	}
	
	/**
	 * 取向导的图片默认图片
	 * @author hunnyhu
	 */
	public class InitDataTask extends AsyncTask<String, Integer, List<JSONObject>> {
		protected Context context;
		protected GridView gridView;
		protected int imageWidth;
		public InitDataTask(Context context, GridView gridView, int imageWidth) {
			this.context = context;
			this.gridView = gridView;
		}
		@Override
		protected List<JSONObject> doInBackground(String... params) {
			if (isCancelled()) {
				return null;
			}
			return HttpUtils.httpGet(Constants.APP_URL + "/assistant/guideJsonLinks.html", null, 
				new HttpUtils.onGetSuccessListener<List<JSONObject>>() {
					@Override
					public List<JSONObject> onSuccess(int status, String result) {
						if (HttpUtils.SC_OK == status) {
							ShareUtils.setPrefs("links", result, context);
							return JSONUtils.getJSONListFromIdentifyString(result, "links");
						}
						return null;
					}
				});
		}
		@Override
		protected void onPostExecute(List<JSONObject> result) {
			hideProgress();
			super.onPostExecute(result);
			if (null == result || result.isEmpty()) {
				List<JSONObject> ls = JSONUtils.getJSONListFromIdentifyString(ShareUtils.getPrefs("links", context), "links");
				if (null != ls && !ls.isEmpty()) {
					result = ls;
				} else {
					Toast.makeText(context, "未能加载到数据", Toast.LENGTH_SHORT).show();
					return;
				}
			}
			GuideGridAdapter guideGridAdapter = new GuideGridAdapter(context, result, imageWidth);
			gridView.setAdapter(guideGridAdapter);
		}
	}
	
	public class InitGuideAdvertisementDataTask extends AsyncTask<String, Integer, List<JSONObject>> {
		protected Context context;
		protected ViewPager viewPager;
		public InitGuideAdvertisementDataTask(Context context, ViewPager viewPager) {
			this.context = context;
			this.viewPager = viewPager;
		}
		@Override
		protected List<JSONObject> doInBackground(String... params) {
			if (isCancelled()) {
				return null;
			}
			return HttpUtils.httpGet(Constants.APP_URL + "/assistant/guideJsonAdbanner.html", null, 
					new HttpUtils.onGetSuccessListener<List<JSONObject>>() {
						@Override
						public List<JSONObject> onSuccess(final int status, String result) {
							if (HttpUtils.SC_OK == status) {
								return JSONUtils.getJSONListFromIdentifyString(result, "adList");
							} else {
								Log.i("HttpClient", status + "");
							}
							return null;
						}
					});
		}
		@Override
		protected void onPostExecute(List<JSONObject> result) {
			super.onPostExecute(result);
			GuideAdvertisementAdapter adapter = new GuideAdvertisementAdapter(context, result);
			if (adapter.init()) {
				this.viewPager.setAdapter(adapter);
				Message msg = new Message();
				Bundle bundle = new Bundle();
				bundle.putInt("count", adapter.getCount());
				msg.setData(bundle);
				msg.what = 1;
				advertisement.sendMessage(msg);
				this.viewPager.setOnPageChangeListener(new GuidAdvertisementChangeListener());
			}
		}
	}
	
	public class GuideAdvertisementAdapter extends PagerAdapter {
		protected Context context;
		protected List<JSONObject> list;
		protected List<View> listView;
		protected ImageLoader imgLoader;
		public GuideAdvertisementAdapter(Context context, List<JSONObject> list) {
			this.list = list;
			this.context = context;
			listView = new ArrayList<View>();
			imgLoader = new ImageLoader(context, ContextUtils.getScreenWidth(context));
		}
		public boolean init() {
			if (null == list || list.isEmpty()) {
				return false;
			}
			for (int i = 0; i < list.size(); i ++) {
				JSONObject object = list.get(i);
				String id = null;
				String type = null;
				String adId = null;
				ViewHolder holder = null;
				holder = new ViewHolder();
				id = JSONUtils.getStringFromJSONObject(object, "adRefId");//图片ID
				type = JSONUtils.getStringFromJSONObject(object, "adType");//广告类型
				adId = JSONUtils.getStringFromJSONObject(object, "refId");//广告关键ID
				holder.setId(id);
				holder.setType(type);
				holder.setAdId(adId);
				if (null == id || null == type || null == adId) {
					continue;
				}
				ImageView imageView = new ImageView(context);
				imageView.setScaleType(ImageView.ScaleType.FIT_XY);
				imageView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
				imgLoader.displayImage(Constants.APP_URL + "/assistant/image.html?id=" + id, imageView);
				imageView.setTag(holder);
				imageView.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						ViewHolder vh = (ViewHolder)v.getTag();
						String adType = vh.getType();
						Intent intent = null;
						if ("0".equals(adType)) {//产品类型
							intent = new Intent(context, ProductItemActivity.class);
						} else if ("1".equals(adType)) {//求购类型
							intent = new Intent(context, PurchaseItemActivity.class);
						} else if ("2".equals(adType)) {//公司类型
							intent = new Intent(context, CompanyItemActivity.class);
						} else {
							Toast.makeText(context, "未知的广告类型", Toast.LENGTH_SHORT).show();
							return;
						}
						intent.putExtra("id", vh.getAdId());
						context.startActivity(intent);
					}
				});
				listView.add(imageView);
			}
			return true;
		}
		@Override
		public int getCount() {
			return listView.size();
		}
		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;
		}
		@Override
		public void destroyItem(View arg0, int arg1, Object arg2) {
			((ViewPager) arg0).removeView(listView.get(arg1));
		}
		@Override
		public Object instantiateItem(View arg0, int arg1) {
			((ViewPager) arg0).addView(listView.get(arg1));
			return listView.get(arg1);
		}
	}
	
	public class GuidAdvertisementChangeListener implements OnPageChangeListener {
		@Override
		public void onPageScrollStateChanged(int arg0) {}
		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {}
		@Override
		public void onPageSelected(int arg0) {
			if (null == imageIndicator || imageIndicator.length == 0) {
				return;
			}
			for (int i = 0; i < imageIndicator.length; i++) {
				if (arg0 != i) {
					imageIndicator[i].setBackgroundResource(R.drawable.page_indicator);
				}
			}
			imageIndicator[arg0].setBackgroundResource(R.drawable.page_indicator_focused);
		}
	}
	
	protected class ViewHolder {
		protected String id = null;
		protected String type = null;
		protected String adId = null;
		public String getId() {
			return id;
		}
		public void setId(String id) {
			this.id = id;
		}
		public String getType() {
			return type;
		}
		public void setType(String type) {
			this.type = type;
		}
		public String getAdId() {
			return adId;
		}
		public void setAdId(String adId) {
			this.adId = adId;
		}
	}

}
